<?php
/**
 * 物资出库单跟出库记录
 */
namespace App\Http\Controllers\Api;
use App\Model\MessageText;
use App\Model\Stock;
use App\Model\MaterialList;
use App\Model\Users;
use App\Model\WarehouseMaterials;
use App\Model\Checkcategory;
use App\Model\Company;
use App\Model\WarehouseOutbound;
use App\Model\WarehouseOutboundDetail;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpWord\Element\Table;
use PhpOffice\PhpWord\SimpleType\TblWidth;
use PhpOffice\PhpWord\TemplateProcessor;

class WarehouseOutboundController extends Controller
{
    /**
     * 物资出库单记录列表数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function listData(Request $request)
    {
        $query = $this->pub($request);
        $res=$query->paginate($request->get('limit',15))->toArray();
        $get_warehouse_type = WarehouseOutbound::get_outbound_type();  //出库性质
        /*foreach ($res['data'] as $key=>$val){
            if(isset($val['warehouse_outbound_detail'])){
                foreach ($val['warehouse_outbound_detail'] as $wk=>$wv){
                    if(isset($wv['stock'])){
                        if(empty($wv['stock']['material_list']) || empty($wv['stock']['goods'])){
                            unset($res['data'][$key]);
                        }
                    }
                }
            }
        }*/

        $res_arr['data']['list'] = $res['data'];
        $res_arr['data']['count'] = $res['total'];
        $res_arr['data']['get_warehouse_type'] = $get_warehouse_type;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资出库单记录列表数据
     * @param $request
     * @return array
     */
    public function pub($request){
        $user = Auth::user();
        $role = $user->role;
        $community = $user->community;

        $name = $request['name'];
        $goods_id = $request['goods_id']??0;
        $query = WarehouseOutbound::with([
            'warehouseOutboundDetail',
            'Users:id,name',
            'warehouseOutboundDetail.stock:id,goods_id,material_id,checkcategory_id,company_id',
            'warehouseOutboundDetail.stock.checkcategory:id,name',
            'warehouseOutboundDetail.stock.goods:id,name',
            'warehouseOutboundDetail.stock.company:id,comName,community',
            'warehouseOutboundDetail.stock.materialList:id,name'])
            ->whereHas('warehouseOutboundDetail.stock.goods' , function ($q) use ($goods_id) {
                if($goods_id){
                    $q->where('id', $goods_id);
                }
            })->whereHas('warehouseOutboundDetail.stock.materialList' , function ($q) use ($name) {
                if($name){
                    $q->where('name', 'like', '%' . $name . '%');
                }
            });
        if(Users::iscommunity($role)){
            $query = $query->whereHas('warehouseOutboundDetail.stock.company', function ($q) use ($community) {
                $q->where('community', $community);
            });
        }
       /* if(isset($request['name']) && $name = $request['name']){  //物资名称
            $query->where('warehouseMaterials.materialList.name','like','%'.$name.'%');
        }*/
        if($role=='community_admin'){
            $query = $query->whereHas('warehouseOutboundDetail.stock.company', function ($q) use ($community) {
                $q->where('community', $community);
            });
        }

        if(isset($request['type']) && $type = $request['type']){ //出库类型
            $query = $query->where('type',$type);
        }
        if(isset($request['start_created_at']) && $start_created_at = $request['start_created_at']){  //开始时间
            $query = $query->where('created_at','>=',$start_created_at);
        }
        if(isset($request['end_created_at']) && $end_created_at = $request['end_created_at']){  //结束时间
            $query = $query->where('created_at','<=',$end_created_at);
        }
        $query = $query->orderby('id','desc');
        return $query;
    }

    /**
     * 导出物物资出库单记录列表
     * @param Request $request
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function exportone(Request $request)
    {
        $query = $this->pub($request);
        $dataExpor= $query->get()->toArray();
        foreach ($dataExpor as $key=>$val){
            foreach ($val['warehouse_outbound_detail'] as $wk=>$wv){
                $wv['order'] = $val['order'];
                $wv['cause'] = $val['cause'];
                $wv['created_at'] = $val['created_at'];
                $wv['type'] = WarehouseOutbound::get_outbound_type($val['type']);
                $wv['user_name'] = $val['users']['name'];
                $wv['goods_name'] = $wv['stock']['goods']['name']??'';
                $wv['material_list_name'] = $wv['stock']['material_list']['name']??'';
                $wv['checkcategory_name'] = $wv['stock']['checkcategory']['name']??'';
                $data[]=$wv;
            }
        }

        $excel = new \PHPExcel();
        $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet = $excel->getActiveSheet();
        $letter = array('A','B','C','D','E','F','G','H','I','J');
        $title = [
            'A1'=>'序 号',
            'B1'=>'出库单号',
            'C1'=>'出库时间',
            'D1'=>'物资分类',
            'E1'=>'物资名称',
            'F1'=>'所属单位（人）',
            'G1'=>'出库数量',
            'H1'=>'出库类型',
            'I1'=>'出库事由',
            'J1'=>'申请人',
        ];
        foreach ($title as $tk=>$tv){
            $objActSheet->setCellValue($tk,$tv);
        }

        foreach ($letter as $l){
            $objActSheet->getStyle($l.'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
        }

        /**填充内容*/
        $orirow = 2;
        $i = 1;

        foreach ($data as &$val) {
            $objActSheet->setCellValue("A".$orirow,$i);
            $objActSheet->setCellValue("B".$orirow,$val['order']??'');
            $objActSheet->setCellValue("C".$orirow,$val['created_at']??'');
            $objActSheet->setCellValue("D".$orirow,$val['goods_name']??'');
            $objActSheet->setCellValue("E".$orirow,$val['material_list_name']??'');
            $objActSheet->setCellValue("F".$orirow,$val['checkcategory_name']??'');
            $objActSheet->setCellValue("G".$orirow,$val['number']??'');
            $objActSheet->setCellValue("H".$orirow,$val['type']??'');
            $objActSheet->setCellValue("I".$orirow,$val['cause']??'');
            $objActSheet->setCellValue("J".$orirow,$val['user_name']??'');

            $i ++;
            $orirow ++;

        }
        /**填充内容*/
        //统一设置填充内容左右居中、字号、宽度
        foreach ($letter as $l){
            for ($x = 2;$x<=$orirow;$x++){
                /*$objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
                $objActSheet->getStyle($l.'2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中*/
                if($l=='A'){
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                }else{
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
                }
                $objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal($setHorizontal);
                $objActSheet->getStyle($l.$x)->getFont()->setSize(10);
                $objActSheet->getColumnDimension($l)->setWidth(20);

            }

        }
        /*$objActSheet->getColumnDimension('B')->setWidth(50);
        $objActSheet->getColumnDimension('C')->setWidth(50);
        $objActSheet->getColumnDimension('J')->setWidth(50);*/
        for ($x=1; $x<=($orirow); $x++) {
            $objActSheet->getRowDimension($x)->setRowHeight(30);//统一设置行高度

        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        $objActSheet->getStyle('A1:J1'.($orirow))->applyFromArray($styleArray);//设置粗边框


        $write = new \PHPExcel_Writer_Excel5($excel);
        ob_end_clean();
        //$date = Carbon::now()->toDateString();//表名前缀日期
        $date=time();
        $filename = '物资出库记录表-'.$date;
        $path = '/storage/excel/'.$filename.'.xls';
        $res = $write->save(public_path().$path);
        return response()->json(['code'=>0,'msg'=>'导出成功','url'=>'http://'.$_SERVER['HTTP_HOST'].$path,'file_name'=>$filename]);
    }

    /**
     * 物资出库记录的单个出库单（新增）
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function outboundOrderData(Request $request)
    {
        //修改的话该值有值
        $id = isset($request['id']) ? $request['id'] : 0;
        $outbound = WarehouseOutbound::with([
            'warehouseOutboundDetail',
            'Users:id,name',
            'warehouseOutboundDetail.stock:id,goods_id,material_id,checkcategory_id,company_id,unit,norms',
            'warehouseOutboundDetail.stock.checkcategory:id,name',
            'warehouseOutboundDetail.stock.goods:id,name',
            'warehouseOutboundDetail.stock.company:id,comName,leader',
            'warehouseOutboundDetail.stock.materialList:id,name,remarks'])->where('id', $id)->first();

        $res_arr['data']['outbound'] = $outbound;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资出库页面
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function referweb(Request $request)
    {
        //修改的话该值有值
        $id = isset($request['id']) ? $request['id'] : 0;
        $warehouseMaterials = WarehouseOutboundDetail::with(['stock:id,goods_id,material_id,checkcategory_id,company_id,unit,norms,warehouse','stock.checkcategory:id,name','stock.goods:id,name','stock.materialList:id,name','stock.company:id,comName,address'])->where('outbound_id', $id)->get()->toArray();
        $res_arr['data']['warehouseOutbound'] = $warehouseMaterials;

        $get_outbound_type = WarehouseOutbound::get_outbound_type(); //出库类型
        //出库单名称
        $user = Auth::user();
        $companyId = $user->companyId;  //当前用户所属企业
        $company = Company::with(['checkcategory'])->find($companyId);

        $res_arr['data']['get_outbound_type'] = $get_outbound_type;
        $res_arr['data']['warehouse_name'] = $company['checkcategory']['name']??'';
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资出库数据处理
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function refer(Request $request)
    {
        $redata = $request->all();
        /*$redata['outbound'] = [[
            'stock_id'=>1,
            'number'=>1,
        ],[
            'stock_id'=>1,
            'number'=>2,
        ]];*/

        $id = isset($redata['id']) ? $redata['id'] : 0;
        $user = Auth::user();
        $userid = $user->id;
        $companyids = [];
        DB::beginTransaction();
        $order_data = WarehouseOutbound::where('id',$id)->first();
        $insert_order['type'] = $redata['type'];  //出库类型
        $insert_order['cause'] = $redata['cause'];  //出库事由
        $insert_order['applicant'] = $redata['applicant']??'';    //申请人
        if($order_data){
            $order_id = $id;
            Stock::operate_del($id,2);
            $warehouseOrder = WarehouseOutbound::where('id', $order_id)->update($insert_order);
            //$resu = WarehouseOutboundDetail::where('outbound_id', $id)->delete();
        }else{
            $insert_order['user_id'] = $userid;  //经办人
            $insert_order['odd_numbers'] = $redata['odd_numbers']??'';    //单号：出库类型outbound_type为2：盘点单号；
            $insert_order['applicant_sign'] = $redata['applicant_sign']??'';  //经办人签字,图片url，只有app用到
            $insert_order['created_at'] = date('Y-m-d H:i:s');
            $url = $request->url();
            if(strstr($url,'/api/')){
                $insert_order['isapp'] = 1;
            }
            $order_id = WarehouseOutbound::insertGetId($insert_order);
            if($order_id){
                $order = WarehouseOutbound::getorders($order_id);
                $update_order['order'] = $order;
                $warehouseOrder = WarehouseOutbound::where('id', $order_id)->update($update_order);
                if(!$warehouseOrder){
                    DB::rollBack();
                    $res_arr["code"] = 408;
                    $res_arr["message"] = 'fail，出库单更新失败';
                    return response()->json($res_arr);
                }
            }else{
                DB::rollBack();
                $res_arr["code"] = 408;
                $res_arr["message"] = 'fail，出库单添加失败';
                return response()->json($res_arr);
            }
        }
        if (!is_array($redata['outbound'])){
            $redata['outbound'] = json_decode($redata['outbound'],true);
        }
        foreach ($redata['outbound'] as $vkey=>$vm) {
            if(!$vm['number']){
                DB::rollBack();
                $res_arr["code"] = 408;
                $res_arr["message"] = 'fail，出库数不能为0为空';
                return response()->json($res_arr);
            }
            $ruserData['outbound_id'] = $order_id;
            $ruserData['stock_id'] = $vm['stock_id'];
            $ruserData['number'] = $vm['number'];
            $ruserData['outbound_type'] = $redata['type'];
            $ruserData['created_at'] = date('Y-m-d H:i:s');
            $ruserData['odd_numbers'] = $redata['odd_numbers']??'';  //单号：出库类型outbound_type为2：盘点单号；
            $ruserData['user_id'] = $userid;  //经办人
            $res = WarehouseOutboundDetail::insertGetId($ruserData);
            if(!$res){
                DB::rollBack();
                $res_arr["code"] = 408;
                $res_arr["message"] = 'fail，出库明细添加失败';
                return response()->json($res_arr);
            }
            $stock= Stock::find($vm['stock_id']);
            if(!$stock){
                DB::rollBack();
                $res_arr["code"] = 408;
                $res_arr["message"] = 'fail，物资明细不存在';
                return response()->json($res_arr);
            }
            $ope = Stock::operate($stock['goods_id'],$stock['material_id'],$stock['checkcategory_id'],$stock['company_id'],2,$redata['type']);
            if(!$ope){
                $getstock= Stock::with([
                    'materialList:id,name',
                ])->where('id',$vm['stock_id'])->first();
                DB::rollBack();
                $res_arr["code"] = 408;
                $res_arr["message"] = $getstock->materialList->name.'库存不足，请联系管理员';
                return response()->json($res_arr);
            }
            $companyids[] = $stock['company_id'];
        }

        DB::commit();
        $request['id'] = $order_id;
        $getpath = $this->outbound_imports($request);
        //发送消息
        MessageText::addmess($getpath,$companyids);

        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资出库数据删除
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function outbound_del(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        Stock::operate_del($id,2);
        WarehouseOutbound::where('id', $id)->delete();
        //WarehouseOutboundDetail::where('outbound_id', $id)->delete();
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 导出出库单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \PhpOffice\PhpWord\Exception\Exception
     */
    public function outbound_import(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        /*读取数据*/
        $templateProcessor =  new TemplateProcessor('./word/template/出库单.docx');
        $data = $this->outboundOrderData($request);
        $data = json_decode(json_encode($data), true);
        $outbound = $data['original']['data']['outbound']??[];
        $templateProcessor->setValue('created_at', date('Y年m月d日',strtotime($outbound['created_at'])));
        $templateProcessor->setValue('order', $outbound['order']);

        $applicant_sign=$outbound['applicant_sign'];
        if($applicant_sign && file_exists('.'.$applicant_sign)){
            $templateProcessor->setImageValue('user_name', '.'.$applicant_sign);
        }else{
            $templateProcessor->setValue('user_name', '');
        }

        $checkcategory_name=$company_name='';
        $count_num = 0;
        $user_name = $outbound['users']['name']??'';
        if (isset($outbound['warehouse_outbound_detail'])){
            $templateProcessor->cloneRow('numb', count($outbound['warehouse_outbound_detail']));
            foreach($outbound['warehouse_outbound_detail'] as $k=>$v) {
                $stock = $v['stock'];
                $checkcategory_name = $stock['checkcategory']['name']??'';

                $leader = $stock['company']['leader']??'';
                $company_name = $stock['company']['comName']??'';
                $tmp_arr['goods_name'] = $stock['goods']['name']??'';
                $tmp_arr['material_name'] = $stock['material_list']['name']??'';
                $tmp_arr['number'] = $v['number']??'';
                $tmp_arr['unit'] = $v['unit']??'';
                $tmp_arr['norms'] = $v['norms']??'';
                $tmp_arr['remarks'] = $stock['material_list']['remarks']??'';
                $count_num = $count_num + $tmp_arr['number'];
                $templateProcessor->setValue('numb#'.($k+1), $k+1);
                //$templateProcessor->style($kk, $vv);
                foreach($tmp_arr as $kk=>$vv) {
                    $templateProcessor->setValue($kk.'#'.($k+1), $vv);
                }
            }
            $templateProcessor->setValue('checkcategory_name', $checkcategory_name);
            $templateProcessor->setValue('company_name', $company_name);
            $templateProcessor->setValue('count_num', $count_num);
            //$templateProcessor->setValue('user_name', $user_name);
            $templateProcessor->setValue('leader', '');
            $templateProcessor->setValue('cause', $outbound['cause']);
        }

        $time = time();
        $name="出库单_".$time;
        $path = "./storage/word/".$name.".docx";
        $templateProcessor->saveAs($path);

        return response()->json(['data' => $path,'code' => 200], 200);
    }

    /**
     * 导出出库单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \PhpOffice\PhpWord\Exception\Exception
     */
    public function outbound_imports(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        /*读取数据*/
        $templateProcessor =  new TemplateProcessor('./word/template/出库单.docx');
        $data = $this->outboundOrderData($request);
        $data = json_decode(json_encode($data), true);
        $outbound = $data['original']['data']['outbound']??[];
        $templateProcessor->setValue('created_at', date('Y年m月d日',strtotime($outbound['created_at'])));
        $templateProcessor->setValue('order', $outbound['order']);

        $applicant_sign=$outbound['applicant_sign'];
        $file_exists = (@fopen($applicant_sign, "r")) ? true : false;
        if($applicant_sign && $file_exists){
            $templateProcessor->setImageValue('user_name', $applicant_sign);
        }else{
            $templateProcessor->setValue('user_name', '');
        }
        $checkcategory_name=$company_name='';
        $count_num = 0;
        $user_name = $outbound['users']['name']??'';

        $cellRowSpan = array('vMerge' => 'restart', 'valign' => 'center'); // 设置可跨行，且文字在居中
        $cellRowContinue = array('vMerge' => 'continue'); //使行连接，且无边框线
        $cellVCentered = array('valign' => 'center'); //居中
        $cellHCentered = array('align' => 'center'); //居中
        $cellHCentered1 = array('align' => 'left'); //
        $fontStyle = array('size'=>12,'bold'=>true,'valign'=>'center','align'=>'center','name'=>'宋体');
        $fontStyle1 = array('size'=>12,'valign'=>'center','align'=>'center','name'=>'宋体');
        $contentStyle = array('size'=>11,'valign'=>'left','align'=>'left','name'=>'宋体');
        $cellColSpan3 = array('gridSpan' => 3, 'valign' => 'center'); //设置跨列
        $cellColSpan4 = array('gridSpan' => 4, 'valign' => 'center'); //设置跨列
        $table = new Table(array('borderSize' => 6, 'borderColor' => 'black', 'width' => 8500, 'unit' => TblWidth::TWIP)); //array('borderSize' => 6, 'borderColor' => 'black', 'width' => 9500, 'unit' => TblWidth::TWIP)

        /*添加table头部*/
        $table->addRow(600);  //添加一行
        /*$table->addCell(5000,$cellHCentered)->addText("姓名",$styleFoun,$cellHCentered);*/
        $table->addCell(4000, $cellRowSpan)->addText('类 别',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(4000, $cellRowSpan)->addText('序 号',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(7000, $cellRowSpan)->addText('物品名称',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(5000, $cellRowSpan)->addText('数 量',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(5000, $cellRowSpan)->addText('单 位',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(5000, $cellRowSpan)->addText('规 格',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(5000, $cellRowSpan)->addText('备 注',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $arrs = [];
        $xh=0;
        if (isset($outbound['warehouse_outbound_detail'])){
            foreach($outbound['warehouse_outbound_detail'] as $k=>$v) {
                $stock = $v['stock'];
                $checkcategory_name = $stock['checkcategory']['name']??'';

                $leader = $stock['company']['leader']??'';
                $company_name = $stock['company']['comName']??'';
                $tmp_arr['goods_name'] = $stock['goods']['name']??'';
                $tmp_arr['material_name'] = $stock['material_list']['name']??'';
                $tmp_arr['number'] = $v['number']??'';
                $tmp_arr['unit'] = $stock['unit']??'';
                $tmp_arr['norms'] = $stock['norms']??'';
                $tmp_arr['remarks'] = $stock['material_list']['remarks']??'';
                $count_num = $count_num + $tmp_arr['number'];
                $templateProcessor->setValue('numb#'.($k+1), $k+1);
                //$templateProcessor->style($kk, $vv);
                $data['table'][]=$tmp_arr;  //正常赋值用于word中的表格遍历
                $data['real_data'][] = $tmp_arr;//算全部合计的时候用
                $arrs[$stock['goods_id']][]=$tmp_arr;
            }
            foreach ($arrs as $k=>$vv){
                foreach ($vv as $kk=>$tmp_arr){
                    $xh++;
                    $kk++;
                    if($kk==1){
                        $table->addRow();  //添加一行
                        $table->addCell(5000, $cellRowSpan)->addText($tmp_arr['goods_name'],$fontStyle1, $cellHCentered); //设置该列可以跨行，且样式居中
                    }else{
                        $table->addRow(500);
                        $table->addCell(null, $cellRowContinue);
                    }
                    $table->addCell(5000, $cellRowSpan)->addText($xh,$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
                    $table->addCell(7000, $cellRowSpan)->addText($tmp_arr['material_name'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中
                    $table->addCell(5000, $cellRowSpan)->addText($tmp_arr['number'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中
                    $table->addCell(5000, $cellRowSpan)->addText($tmp_arr['unit'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中
                    $table->addCell(5000, $cellRowSpan)->addText($tmp_arr['norms'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中
                    $table->addCell(5000, $cellRowSpan)->addText($tmp_arr['remarks'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中
                }
            }
            $templateProcessor->setValue('checkcategory_name', $checkcategory_name);
            $templateProcessor->setValue('company_name', $company_name);
            //$templateProcessor->setValue('count_num', $count_num);
            //$templateProcessor->setValue('user_name', $user_name);
            $templateProcessor->setValue('leader', '');
            //$templateProcessor->setValue('cause', $outbound['cause']);
        }

        $real_data = $data['real_data'];
        unset($data['real_data']);
        // 添加总计
        $table->addRow(600);  //添加一行
        $table->addCell(5000, $cellColSpan3)->addText('总计',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(5000, $cellVCentered)->addText(array_sum(array_column($real_data,'number')),$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 //
        $table->addCell(5000, $cellVCentered)->addText('',$contentStyle, $cellHCentered1);
        $table->addCell(5000, $cellVCentered)->addText('',$contentStyle, $cellHCentered1);
        $table->addCell(5000, $cellVCentered)->addText('',$contentStyle, $cellHCentered1);
        // 添加出库事由
        $table->addRow(600);  //添加一行
        $table->addCell(5000, $cellColSpan3)->addText('出库事由',$fontStyle, $cellHCentered); //设置该列可以跨行，且样式居中
        $table->addCell(5000, $cellColSpan4)->addText($outbound['cause'],$contentStyle, $cellHCentered1); //设置该列可以跨行，且样式居中 //

        $templateProcessor->setComplexBlock('table', $table);

        $time = time();
        $name="出库单_".$time;
        $path = "/storage/word/".$name.".docx";
        $templateProcessor->saveAs('.'.$path);

        $file=$outbound['file'];
        if($file && file_exists('.'.$file)){
            unlink('.'.$file);
        }
        $update_order['file'] = $path;
        $warehouseOutbound = WarehouseOutbound::where('id', $id)->update($update_order);
        return $path;
        //return response()->json(['data' => $path,'code' => 200], 200);
    }

    /**
     * 添加修改时导出出库单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function outbound_import_url(Request $request){
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        $warehouseOrder = WarehouseOutbound::where('id', $id)->first();
        $path = $warehouseOrder->file;
        if(empty($warehouseOrder) || !file_exists('.'.$path)){
            $res_arr["code"] = 408;
            $res_arr["message"] = '该出库单不存在，请联系管理员';
            return response()->json($res_arr);
        }

        return response()->json(['data' => 'http://'.$_SERVER['HTTP_HOST'].$path,'code' => 200], 200);
    }

}
